package cn.geminis.crypto.csp.soft.gm;

import cn.geminis.crypto.core.key.PrivateKey;
import cn.geminis.crypto.core.key.PublicKey;
import cn.geminis.crypto.csp.AbstractAsymmetricBlockCipher;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.engines.SM2Engine;
import org.bouncycastle.crypto.params.ParametersWithRandom;

/**
 * @author Allen
 */
public class Sm2BlockCipher extends AbstractAsymmetricBlockCipher {

    private PublicKey publicKey;
    private PrivateKey privateKey;
    private SM2Engine sm2Engine = new SM2Engine();

    public Sm2BlockCipher(PublicKey publicKey, PrivateKey privateKey) {
        this.publicKey = publicKey;
        this.privateKey = privateKey;
    }

    @Override
    public byte[] getPublicKey() {
        return this.publicKey.getEncoded();
    }

    @Override
    public void close() {
    }

    @Override
    public void init(boolean forEncrypt, CipherParameters cipherParameters) {
        if (forEncrypt) {
            var parameter = new ParametersWithRandom(cipherParameters);
            this.sm2Engine.init(true, parameter);
        } else {
            this.sm2Engine.init(false, this.privateKey.getKeyParameter());
        }
    }

    @Override
    public int getInputBlockSize() {
        return 0;
    }

    @Override
    public int getOutputBlockSize() {
        return this.sm2Engine.getOutputSize(0);
    }

    @Override
    public byte[] processBlock(byte[] bytes, int start, int length) throws InvalidCipherTextException {
        return this.sm2Engine.processBlock(bytes, start, length);
    }
}
